﻿using DevExpress.XtraBars;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraReports.UI;
using EyFramework.Common;
using EyFramework.Common.Utils;
using EyFramework.Library;
using EyFramework.Sys.Core;
using EyFramework.Sys.Entity;
using Ncov2019.Core.Service;
using Ncov2019.Entity;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;

namespace Ncov2019
{
    public partial class FrmNcovOrder : FrmDevBase
    {
        private List<GridColumnInfo> columnInfos = new List<GridColumnInfo>();
        private List<GridColumnInfo> columnInfos2 = new List<GridColumnInfo>();

        private INcovRecordsService ncovRecordsService;
        private INcovOrderRecordService ncovOrderRecordService;
        private INcovUsersService ncovUsersService;
        private ILisService lisService;
        private NcovRecords _NcovRecords;

        public FrmNcovOrder()
        {
            InitializeComponent();
            InitForm();
        }

        private void InitForm()
        {
            scUser.InitUserSelect();
            gvData.ShowRowNum();
            gcData.ShowContextMenu(this.components);//显示右键导出功能
            gvData2.ShowRowNum();
            gcData2.ShowContextMenu(this.components);//显示右键导出功能
            #region
            columnInfos.Add(new GridColumnInfo("ORD_DT", "开单日期", 100));
            columnInfos.Add(new GridColumnInfo("PAT_TYPE", "开单类型", 100));
            columnInfos.Add(new GridColumnInfo("ORDER_USR", "创建人", 100));
            #endregion

            #region
            var col = new GridColumnInfo("ISCHECK", "选择", 50);
            RepositoryItemCheckEdit rice = new RepositoryItemCheckEdit();
            rice.CheckedChanged += Rice_CheckedChanged;
            col.Columnedit = rice;
            col.COL_READONLY = false;
            columnInfos2.Add(col);
            columnInfos2.Add(new GridColumnInfo("CHT_ID", "病历号码", 100));
            columnInfos2.Add(new GridColumnInfo("PAT_NM", "姓名", 100));
            columnInfos2.Add(new GridColumnInfo("SEX", "性别", 100));
            columnInfos2.Add(new GridColumnInfo("ID_NO", "身份证号", 100));
            columnInfos2.Add(new GridColumnInfo("TELPHONE", "联系电话", 100));
            columnInfos2.Add(new GridColumnInfo("DEPARTMENT", "部门", 100));
            columnInfos2.Add(new GridColumnInfo("PAT_TAGS", "人员标记", 100));
            columnInfos2.Add(new GridColumnInfo("ORD_FLAG", "开单标志", 100));
            columnInfos2.Add(new GridColumnInfo("ORD_DT", "开单日期", 100));
            columnInfos2.Add(new GridColumnInfo("ORD_USR_ID", "开单人", 100));
            #endregion
        }

        private void Rice_CheckedChanged(object sender, EventArgs e)
        {
            if (!gvData2.IsNewItemRow(gvData2.FocusedRowHandle))
            {
                gvData2.CloseEditor();
                gvData2.UpdateCurrentRow();
            }
        }

        private void FrmNcovLabCollect_Load(object sender, EventArgs e)
        {
            ncovRecordsService = Globals.GetService<INcovRecordsService>();
            ncovOrderRecordService = Globals.GetService<INcovOrderRecordService>();
            lisService = Globals.GetService<ILisService>();
            ncovUsersService = Globals.GetService<INcovUsersService>();
            dtStart.Text = ncovRecordsService.GetCurrentDate("YYYY-MM-DD");
            dtEnd.Text = dtStart.Text;
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            ShowLoading();
            btnQuery.Enabled = false;
            try
            {
                QueryRecordData();
                //避免多次重复点击按钮触发多次查询检索,清理掉windows的事件消息
                Application.DoEvents();
                CloseLoading();
                btnQuery.Enabled = true;
            }
            catch
            {
                btnQuery.Enabled = true;
                throw;
            }
        }

        private void bbiAdd_ItemClick(object sender, ItemClickEventArgs e)
        {
            FrmNcovOrderEdit frmNcovOrder = new FrmNcovOrderEdit();
            frmNcovOrder.OnDataSaved += FrmNcovOrder_OnDataSaved;
            frmNcovOrder.ShowDialog();
        }

        private void FrmNcovOrder_OnDataSaved(object sender, EventArgs e)
        {
            QueryRecordData();
        }

        private void QueryRecordData()
        {
            var ncovRecordParam = new NcovRecordParam
            {
                START_DT = dtStart.DateTime.ToString("yyyy-MM-dd"),
                END_DT = dtEnd.DateTime.ToString("yyyy-MM-dd"),
            };
            var ncovRecords = ncovRecordsService.QueryBy(ncovRecordParam);
            ncovRecords.ForEach(p =>
            {
                p.PAT_TYPE = SysCache.GetDictVal(p.PAT_TYPE, "ncov_pat_type");
                p.ORDER_USR = SysCache.GetSysUserById(p.ORDER_USR).NICK_NAME;
            });
            gcData.DataSource = ncovRecords;
            DevPublic.SetGridControlView(gvData, columnInfos, true, true);
        }

        private void gvData_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (gvData.FocusedRowHandle >= 0)
            {
                _NcovRecords = (gvData.GetRow(gvData.FocusedRowHandle) as NcovRecords);
                if (_NcovRecords != null)
                {
                    QueryDetailData(_NcovRecords.RECORD_SEQ);
                }
            }
        }

        private void QueryDetailData(long detailDataSeq)
        {
            groupControl3.Text = _NcovRecords.PAT_TYPE + "-" + _NcovRecords.ORD_DT;
            var ncovOrderRecords = ncovOrderRecordService.QueryDataByRecSeq(detailDataSeq);
            ncovOrderRecords.ForEach(p =>
            {
                if (!string.IsNullOrEmpty(p.ORD_USR_ID))
                {
                    p.ORD_USR_ID = SysCache.GetSysUserById(p.ORD_USR_ID).NICK_NAME;
                }
            });
            gcData2.DataSource = ncovOrderRecords;
            DevPublic.SetGridControlView(gvData2, columnInfos2, true, true);
        }

        private void barButtonItem3_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (_NcovRecords == null)
            {
                Globals.ShowError("请先选择左侧需要添加检测对象的开单记录，再添加检测对象！");
                return;
            }
            FrmNcovPatSelect frmNcovPatSelect = new FrmNcovPatSelect(_NcovRecords.RECORD_SEQ);
            if (frmNcovPatSelect.ShowDialog() == DialogResult.OK)
            {
                QueryDetailData(_NcovRecords.RECORD_SEQ);
            }
        }

        private void bbiDelete_ItemClick(object sender, ItemClickEventArgs e)
        {
            gvData2.RefreshData();
            List<NcovOrderRecordDto> orders = new List<NcovOrderRecordDto>();
            for (int i = 0; i < gvData2.RowCount; i++)
            {
                NcovOrderRecordDto nord = gvData2.GetRow(i) as NcovOrderRecordDto;
                if (nord.ISCHECK)
                {
                    orders.Add(nord);
                }
            }
            if (orders.Count == 0)
            {
                Globals.ShowError("请先选择你需要删除的核酸检测对象！");
                return;
            }
            else
            {
                if (ncovOrderRecordService.DeleteOrders(orders))
                {
                    Globals.ShowTips("检测对象删除成功！");
                    QueryDetailData(_NcovRecords.RECORD_SEQ);
                }
            }
        }

        private void bbiClear_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (Globals.ShowYesNoAndWarning("您正在清空所有的核酸检测对象，已开单的检测对象不会清空，是否继续？") == DialogResult.Yes)
            {
                if (ncovOrderRecordService.ClearOrders(_NcovRecords.RECORD_SEQ))
                {
                    Globals.ShowTips("检测对象清空成功！");
                    QueryDetailData(_NcovRecords.RECORD_SEQ);
                }
            }
        }

        private void bbiOrder_ItemClick(object sender, ItemClickEventArgs e)
        {
            List<NcovOrderRecordDto> orders = new List<NcovOrderRecordDto>();
            for (int i = 0; i < gvData2.RowCount; i++)
            {
                NcovOrderRecordDto nord = gvData2.GetRow(i) as NcovOrderRecordDto;
                if (nord.ISCHECK)
                {
                    orders.Add(nord);
                }
            }
            if (orders.Count == 0)
            {
                Globals.ShowError("请先选择你需要开核酸检测对象！");
                return;
            }
            else
            {
                NcovOrder(orders);
            }
        }

        private void NcovOrder(List<NcovOrderRecordDto> ncovOrderRecords)
        {
            if (Globals.ShowYesNoAndTips(string.Format("您确定批量给当前{0}个患者批量开单吗？是否继续？", ncovOrderRecords.Count)) ==
                DialogResult.Yes)
            {
                try
                {
                    //关闭触发器
                    int pOrderIndex = 1;
                    foreach (var ncovOrder in ncovOrderRecords)
                    {
                        ShowLoading("[" + pOrderIndex + "/" + ncovOrderRecords.Count + "],姓名：" + ncovOrder.PAT_NM);
                        try
                        {
                            bool result = ncovOrderRecordService.NcovOrder(ncovOrder);
                            if (!result)
                            {
                                Globals.ShowError("核酸开单失败！");
                            }
                        }
                        catch (Exception ex)
                        {
                            Globals.ShowError(ex.Message);
                        }
                        finally
                        {
                            CloseLoading();
                        }
                        pOrderIndex++;
                    }
                }
                catch (Exception ex)
                {
                    Globals.ShowError(ex.Message);
                }
                finally
                {
                    CloseLoading();
                }
                QueryDetailData(_NcovRecords.RECORD_SEQ);
            }
        }

        private void bbiPrint_ItemClick(object sender, ItemClickEventArgs e)
        {
            List<NcovOrderRecordDto> orders = new List<NcovOrderRecordDto>();
            for (int i = 0; i < gvData2.RowCount; i++)
            {
                NcovOrderRecordDto nord = gvData2.GetRow(i) as NcovOrderRecordDto;
                if (nord.ISCHECK && nord.ORD_DT != null)
                {
                    orders.Add(nord);
                }
            }
            if (orders.Count == 0)
            {
                Globals.ShowError("请先选择你需要打印的,已开单记录！");
                return;
            }
            else
            {
                PrintLabNew(orders);
            }
        }

        private void PrintLabNew(List<NcovOrderRecordDto> orders)
        {
            foreach (NcovOrderRecordDto order in orders)
            {
                if (string.IsNullOrEmpty(order.BAR_NO))
                {
                    if (!ncovOrderRecordService.LisOrder(order))
                    {
                        Globals.ShowError("条码生成失败！");
                        break;
                    }
                }

                LabPrintReport labPrintReport = new LabPrintReport();
                labPrintReport.setData(order);
                labPrintReport.ShowPrintMarginsWarning = false;
                string printerName = Globals.appConfigure.GetConfigureValue("PRINTER", "LAB_PRINTER_NAME", "");
                labPrintReport.PrinterName = printerName;
                labPrintReport.CreateDocument();
                ReportPrintTool printTool = new ReportPrintTool(labPrintReport);
                bool isPreview = bool.Parse(Globals.appConfigure.GetConfigureValue("PRINTER", "LAB_PRINTER_PREVIEW", "true"));
                if (isPreview)
                {
                    labPrintReport.ShowPreview();
                }
                else
                {
                    printTool.Print();
                }
            }
        }

        private void bciCheck_CheckedChanged(object sender, ItemClickEventArgs e)
        {
            for (int i = 0; i < gvData2.RowCount; i++)
            {
                //就用这条语句虽然能直接将界面上的打上勾，但是如果该列正好是排序状态下，行顺序会立即调整，导致此循环混乱
                //所以改用下面两句取出实体，给实体赋值。最后再gdcPassbyArl.RefreshDataSource()更新界面。
                //gdvPassbyArl.SetRowCellValue(i, "选择", checkEdit1.Checked);
                NcovOrderRecordDto arl = gvData2.GetRow(i) as NcovOrderRecordDto;
                arl.ISCHECK = bciCheck.Checked;
            }
            gvData2.RefreshData();
        }

        private void bbiPrintReport_ItemClick(object sender, ItemClickEventArgs e)
        {
            List<NcovUsers> users = ncovUsersService.GetUsersByCompany("杭州市南郊监狱");
            users.ForEach(p =>
            {
                Report.LabResultReport labResultReport = new Report.LabResultReport();
                labResultReport.QueryData(p.CHT_ID);
                labResultReport.ExportToPdf(Path.Combine(DirectoryUtil.GetCurrentDirectory(), p.PAT_NM + "(" + p.CHT_ID + ")" + ".pdf"));
            });
        }
    }
}